package code.rocky.consumer;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class ConsumerDemo04 {

    private static Object lock = new Object();

    private volatile static int COUNT = 1;
    private volatile static int TOTAL = 10;


    public static void main(String[] args) {
        for (int i = 1; i <= 25; i++) {
            Thread p = new Thread(new Producer(), "producer" + i);
            Thread c = new Thread(new Consumer(), "consumer" + i);
            p.start();
            c.start();
        }
    }

    static class Producer implements Runnable {

        @Override
        public void run() {

            synchronized (lock) {
                if (COUNT >= TOTAL) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    producer();
                    lock.notifyAll();
                }
            }
        }

        public void producer() {
            System.out.println(Thread.currentThread().getName() + " 线程 " + " 生产了随机数: " + (++COUNT));
        }
    }

    static class Consumer implements Runnable {

        @Override
        public void run() {
            synchronized (lock) {
                if (COUNT > 0) {
                    consumer();
                    lock.notifyAll();
                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }

        }


        public void consumer() {
            System.out.println(Thread.currentThread().getName() + " 线程 " + " 消费了随机数: " + (--COUNT));
        }
    }
}
